<template>
  <div class="imgs">
    <ul v-if="imageList.length > 1">
      <li
        class="item"
        ref="items"
        v-for="(image, index) in imageList"
        :key="index"
        :style="{
          'background-image': 'url(' + image.url + ')',
        }"
      ></li>
    </ul>
    <ul v-else>
      <li
        class="item static"
        v-for="(image, index) in imageList"
        :key="index"
        :style="{
          'background-image': 'url(' + image.url + ')',
        }"
      ></li>
    </ul>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { getBackImages } from "@/api/backimg/index";
import { backImg } from "@/api/backimg/type";

const imageList = ref<backImg[]>([]);

const getImageList = async () => {
  const res = await getBackImages();
  if (res.status === 200) {
    imageList.value = res.data;
  }
};

getImageList();

const items = ref();

// 如果有多张图片，才使用动画效果
watch(imageList, () => {
  if (imageList.value.length > 1) {
    watch(items, () => {
      items.value.forEach((element: any, index: number) => {
        element.style.animationDuration = `${5 * items.value.length}s`;
        element.style.animationDelay = `${index * 5}s`;
      });
    });
  }
});

onMounted(() => {});
</script>

<style lang="scss" scoped>
@import "@/assets/styles/mixin.scss";
.imgs {
  position: relative;
  width: 100%;
  height: 100vh;
  z-index: 0;
  overflow: hidden;

  .item {
    @include absolute;
    width: 100%;
    height: 100%;
    background: no-repeat 50% 50% / cover;
    opacity: 0;
    animation-name: imageAnimation;
    animation-timing-function: linear;
    animation-iteration-count: infinite;
    animation-timing-function: linear;
    backface-visibility: hidden;
    transform-style: preserve-3d;
  }

  .static {
    opacity: 1; // 如果只有一张图片，保持显示不做动画
    animation: none; // 取消动画效果
  }

  &::before {
    content: "";
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    transition: all 0.2s ease-in-out 0s;
  }
}

@keyframes imageAnimation {
  0% {
    opacity: 0;
    animation-timing-function: ease-in;
  }

  2% {
    opacity: 1;
  }

  8% {
    opacity: 1;
    transform: scale(1.05);
    animation-timing-function: ease-out;
  }

  17% {
    opacity: 1;
    transform: scale(1.1);
  }

  25% {
    opacity: 0;
    transform: scale(1.1);
  }

  100% {
    opacity: 0;
  }
}
</style>
